package com.abel.main.colony;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author abel.he
 * @data 2018/8/9 23:05
 */
public class Producer {

    public static void main(String[] args) {
        sendMessage("colony 集群搭建成功");
    }

    private static void sendMessage(String data) {
        ConnectionFactory factory = null;
        Connection connection = null;
        Session session = null;
        Destination destination = null;
        MessageProducer producer = null;
        Message message = null;

        try {
            factory = new ActiveMQConnectionFactory("admin", "admin",
                    "failover:(tcp://192.168.26.50:61616,tcp://192.168.26.50:61617,tcp://192.168.26.50:61618)?Randomize=false");
            connection = factory.createConnection();
            connection.start();

            session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
            destination = session.createQueue("colony");
            producer = session.createProducer(destination);

            int temp = 1;
            while (true) {
                message = session.createTextMessage(data + temp);
                producer.send(message);
                temp++;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消息发送成功" + data + temp);
            }
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            if (producer != null) {
                try {
                    producer.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
